package com.apes.fn.scm.retailOrder.service.account;

import com.apes.fn.scm.retailOrder.service.account.retail.RetailAccount;
import com.apes.fn.scm.retailOrder.service.account.retailReturn.RetailReturnAccount;
import com.apes.fn.scm.retailReturn.RetailReturn;
import com.apes.scm.voucher.model.Voucher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 零售相关的账目代理类
 *
 * @Author wuq
 * @Date 2021-7-22
 */
@Service
public class RetailRetailAccountService implements ApplicationListener<ContextRefreshedEvent> {

    private static final Map<String, RetailReturnVoucher> map = new ConcurrentHashMap<>();

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        Map<String, Object> retailAccountBean = applicationContext.getBeansWithAnnotation(RetailReturnAccount.class);

        retailAccountBean.forEach((key, value) -> {
            String bizType = value.getClass().getAnnotation(RetailReturnAccount.class).value();
            map.put(bizType, (RetailReturnVoucher) value);
        });
    }

    public Voucher process(String code, RetailReturn retailReturn) {
        if (StringUtils.isEmpty(code)) throw new RuntimeException("传入账目 code 为空，请检查");
        return map.get(code).process(retailReturn);
    }
}
